﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.CrmContacto.Code;
using Web.Framework;
using CrmContacto.WebApp.Code.Sap;
using Web.CrmContacto.Code.Sap;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts.Search;
using CrmContacto.Contracts;
using CrmContacto.Contracts.Contracts;
using Web.CrmContacto.Code.Security;

namespace CrmContacto.WebApp.App
{
    public partial class CustomerSearchMini : BasePage
    {
        private string selectedItems = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!HasPermissionFor(CrmSecurity.CUSTOMERSEARCH_VIEW))
                {
                    ShowMessage(LocalizationProvider.Instance["SinPermisosParaRealizarOperacion"] + CrmSecurity.CUSTOMERSEARCH_VIEW, WebMessageType.Warning);
                }
                else
                {
                    this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.ClientID);

                    if (!this.IsPostBack)
                    {
                        LoadCbos();
                    }
                }
            }
            catch (Exception ex)
            {
                //ExceptionManager.Instance.HandleException(ex); // TODO: sin master no funciona
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        private void LoadCbos()
        {
            List<MaestroBase> listaDeDistribucionList = WebServiceHelper.GetListasDeDistribucion(BaseWebPage.CompanyId);
            UIHelper.LoadLst(listaDeDistribucionList, this.lstListaDistribucion);

            List<MaestroBase> categoriasList = this.GetCategorias(BaseWebPage.CompanyId);
            UIHelper.LoadLst(categoriasList, this.lstCategorias, string.Empty);

            // Campañas
            AccionDeMarketingSearch search = new AccionDeMarketingSearch();
            search.EmpresaId = BasePage.CompanyId;            
            List<AccionDeMarketing> accionesList = WebServiceHelper.GetAccionesDeMarketing(search);
            UIHelper.LoadLst(accionesList, this.lstAccionMarketing, string.Empty);
        }

        public void ShowMessage(string message, WebMessageType type)
        {
            ShowMessage(LocalizationProvider.Instance["Bo.Messages.Mensaje"], message, type);
        }

        public void ShowMessage(string title, string message, WebMessageType type)
        {
            this.pnlMessages.CssClass = "pnlMessagesClass displayBlock";
            this.txtErrorTitle.Text = title;
            this.txtMessages.Text = message;
            if (type != WebMessageType.Error)
            {
                pnlError.CssClass = "errorPanelMessage";
            }
            else
            {
                pnlError.CssClass = "errorPanelError";
            }
        }

        private void Buscar()
        {
            string nombre = this.txtNombre.Text;
            string apellido = this.txtApellido.Text;
            string email = this.txtEmail.Text;

            bool sinLista = UIHelper.GetIntFromInputLst(this.lstListaDistribucion).Count == 0;
            bool sinCategoria = UIHelper.GetIntFromInputLst(lstCategorias).Count == 0;
            bool sinAccion = UIHelper.GetIntFromInputLst(lstAccionMarketing).Count == 0;

            if (String.IsNullOrEmpty(nombre) && String.IsNullOrEmpty(apellido) && String.IsNullOrEmpty(email) && sinLista && sinCategoria && sinAccion)
            {
                ShowMessage(LocalizationProvider.Instance["Bo.CustomerSearchMini.ValidacionInputs"], WebMessageType.Error);
            }
            else
            {
                CustomerSearchParam search = new CustomerSearchParam();
                search.EmpresaId = BasePage.CompanyId;

                search.ConEmail = null;
                search.ConDocumento = null;
                search.ConVentas = null;
                search.SortIsAsc = true;
                search.SortingField = "Email";
                search.PageSize = 0;                
                search.PageSkip = 0;
                search.Email = email;
                search.Nombre = nombre;
                search.Apellido = apellido;
                search.PageSize = 500; // Fuerzo a 500 resultados
                search.ListasDeDistribucion.AddRange(UIHelper.GetIntFromInputLst(this.lstListaDistribucion));
                search.Categorias.AddRange(UIHelper.GetIntFromInputLst(lstCategorias));
                search.AccionesDeMarketingList.AddRange(UIHelper.GetIntFromInputLst(lstAccionMarketing));
                ClienteSearchResult searchResult = WebServiceHelper.GetCustomers(search);

                this.Grid.DataSource = searchResult.Resultados;
                this.Grid.DataBind();

                string resultStr = string.Format(LocalizationProvider.Instance["Bo.SearchContacto.ResultString"], searchResult.TotalDeResultados);
                lblSearchResult.Text = resultStr;

                pnlResults.Visible = true;
                pnlResultsGroup.Visible = true;
            }
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        protected void Grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.Grid.PageIndex = e.NewPageIndex;

                Buscar();
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ShowMessage(ExceptionManager.Instance.GetExceptionMessage(ex) + ExceptionManager.Instance.GetExceptionStackTrace(ex), WebMessageType.Error);
            }
        }        
    }
}